﻿using NHibernate;
using NPersistence;

namespace EstimateTracker.DataAccess
{
    public class PersistenceManager : IPersistenceManager
    {
        private readonly EntityManagerFactory _factory;
        private EntityManager _manager;

        public PersistenceManager()
        {
            _factory = Persistence.CreateEntityManagerFactory("persistenceUnit");
        }

        public TypedQuery<T> GetNamedQuery<T>(string name)
        {
            return Manager.CreateNamedQuery<T>(name,typeof(T));
        }

        public Query GetQuery(string name)
        {
            return Manager.CreateQuery(name);
        }

        public ICriteria BuildCriteria<T>() where T : class 
        {
            return ((ISession) Manager.GetDelegate()).CreateCriteria<T>();
        }

        public EntityTransaction Transaction
        {
            get { return Manager.GetTransaction(); }
        }

        public void Persist(object entity)
        {
            Manager.Persist(entity);
        }

        private EntityManager Manager
        {
            get
            {
                _manager = _manager != null && _manager.IsOpen() ? 
                _manager : _factory.CreateEntityManager();
                return _manager;
            }
        }
    }
}